﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdateService.Mgr.Handler
{
    using System.IO;
    using AutoUpdate.Model.Packet;
    public class uploadFileHandler : Handler
    {
        public uploadFileHandler()
        {
            this.name = "uploadFile";
        }

        public override void doAction(Packet packet)
        {
            string versionPath = Environment.CurrentDirectory + "\\" + ConfigMgr.getInstance().config.versionPath;

            if (!Directory.Exists(versionPath))
            {
                Directory.CreateDirectory(versionPath);
            }

            AutoUpdate.Model.Model.fileTransfer.fs_inodeContent inodeModel = AutoUpdate.Utility.Helper.JsonHelper.getObject<AutoUpdate.Model.Model.fileTransfer.fs_inodeContent>(packet.MessageContent);

            if (inodeModel != null)
            {
                if (!Directory.Exists(versionPath + "\\" + "ver" + inodeModel.version))
                {
                    Directory.CreateDirectory(versionPath + "\\" + "ver" + inodeModel.version);
                }

                string fileName = versionPath + "\\" + "ver" + inodeModel.version + "\\" + inodeModel.md5;

                if (inodeModel.offset == 0)
                {
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                }

                AutoUpdate.Utility.Helper.FileHelper.fileWrite(fileName, inodeModel.offset, inodeModel.length, inodeModel.contents);

                if (inodeModel.length + inodeModel.offset == inodeModel.fileLength)
                {
                    string md5 = AutoUpdate.Utility.Helper.FileHelper.fileMd5(fileName);

                    Console.WriteLine("md5 => " + md5);

                    Console.WriteLine("file md5 => " + inodeModel.md5);

                    if (md5 == inodeModel.md5)
                    {
                        Console.WriteLine(md5);
                    }
                    else
                    {
                        Console.WriteLine("md5 error");
                    }
                }

                inodeModel.contents = null;

                AutoUpdate.Model.Packet.ResponsePacket response = new ResponsePacket();

                packet.FillData(response);

                response.PacketType = PacketType.Response;

                response.MessageContent = Newtonsoft.Json.JsonConvert.SerializeObject(inodeModel);

                ClientMgr.getInstance().transferMessage(response);

            }
        }
    }
}
